package com.jy.appmarket.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.os.AsyncTask;

import com.jy.app.market.idata.data.AppUpdate;
import com.jy.app.market.idata.data.UpdateInfo;
import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.database.AppUpdateDatabase;
import com.jy.appmarket.model.AppUpdateModel;
import com.jy.appmarket.model.UpdateModel;
import com.jy.appmarket.network.engine.AppUpdateNetEngine;
import com.jy.appmarket.network.engine.BaseNetEngine;
import com.jy.appmarket.network.resultdata.AppUpdateResult;
import com.jy.appmarket.network.resultdata.BaseResultData;
import com.jy.appmarket.network.task.NetTask;
import com.jy.appmarket.network.task.NetTask.NetTaskListener;
import com.jy.appmarket.notification.AppUpdateNotification;

public class AppUpdateTask extends AsyncTask<Integer, Void, UpdateModel> implements NetTaskListener {
	private static final String TAG = "AppUpdateTask";
	private final Context mContext;
	private NetTask mUpdateTask;
	private boolean mRunning;

	public AppUpdateTask(Context context) {
		this.mContext = context;
		mRunning = false;
	}

	public boolean isRunning() {
		return mRunning;
	}

	@Override
	protected UpdateModel doInBackground(Integer... params) {
		mRunning = true;
		return AppUpdateUtils.getUpdateModel(mContext);
	}

	@Override
	protected void onPostExecute(UpdateModel result) {
		if (result == null) {
			LogUtil.d(TAG, "result is empty");
			mRunning = false;
			return;
		}

		int sys = result.getSysApps() == null ? 0 : result.getSysApps().size();
		int user = result.getUserApps() == null ? 0 : result.getUserApps().size();
		LogUtil.d(TAG, "sys:" + sys + " user:" + user);

		AppUpdateNetEngine engine = new AppUpdateNetEngine(result);
		mUpdateTask = new NetTask(mContext, engine, 0);
		mUpdateTask.setListener(this);
		new Thread(mUpdateTask).start();
	}

	@Override
	public void onTaskRunSuccessful(int tag, BaseNetEngine engine) {
		BaseResultData result = engine.getResultData();
		AppUpdateResult updateResult = (AppUpdateResult) result;
		if (updateResult.isOK()) {
			AppUpdate appupdate = updateResult.getAppUpdate();

			if (appupdate != null && appupdate.getUpdates() != null) {
				LogUtil.d(TAG, "update count:" + appupdate.getUpdates().size());
				updateAppUpdateDataBase(appupdate.getUpdates());
			}
			Calendar calendar = Calendar.getInstance();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
			String date = dateFormat.format(calendar.getTime());
			Prefs.saveRequestAppUpdateTime(mContext, date);
			Prefs.saveAppUpdateNextQueryTime(mContext, appupdate.getNextQuery());
			if (AppMarketApplication.appUpdateNotificationShowing) {
				AppUpdateNotification.showAppUpdateNotificationImmediately(mContext);
			} else {
				AppUpdateNotification.showAppUpdateNotification(mContext);
			}
		} else {
			LogUtil.d(TAG, "get update failed");
		}
		mRunning = false;
	}

	@Override
	public void onTaskRunError(int tag) {
		mRunning = false;
	}

	@Override
	public void onTaskRunCanceled(int tag) {
		mRunning = false;
	}

	/**
	 * 更新数据库 <br>
	 * 1.本地没有的，直接增加 <br>
	 * 2.本地存在<br>
	 * a：如果版本号一样，则记下之前的最后更新时间和忽略字段<br>
	 * b：版本号不一样，直接更新
	 */
	private void updateAppUpdateDataBase(List<UpdateInfo> updateInfos) {

		AppUpdateDatabase localDataBase = AppUpdateDatabase.getInstance(mContext);
		localDataBase.correctAppUpdatesDatas(mContext);
		List<AppUpdateModel> localAll = localDataBase.getAllUpdatesOrderBy(null, false, true);
		localDataBase.clear();
		boolean localFlag; // 标识本地数据库是否存在该apk的更新数据
		for (UpdateInfo updateInfo : updateInfos) {
			localFlag = false;
			for (AppUpdateModel updateModel : localAll) {
				if (updateInfo.getPackageName().equals(updateModel.getPackageName())) {
					// 本地数据库存在该apk
					localFlag = true;
					if (updateInfo.getVersionCode() != updateModel.getVersionCode()) {
						// 版本不一样，直接插入新的数据
						localDataBase.insert(new AppUpdateModel(updateInfo));
					} else {
						// 版本一样，记录本地的Ignore和LastModification字段
						AppUpdateModel localData = new AppUpdateModel(updateInfo);
						localData.setIgnore(updateModel.isIgnore());
						localDataBase.insert(updateModel);
					}
					break;
				}
			}
			if (!localFlag) { // 本地数据库不存在，直接插入新数据
				localDataBase.insert(new AppUpdateModel(updateInfo));
			}
		}
	}
}